﻿//时间 几天前 几分钟前
function getDateTimeStamp(dateStr){
    dateStr=dateStr.match(/[0-9\-T\:]+/)[0].replace(/T/g,' ');
    return Date.parse(dateStr.replace(/-/gi,"/"));
}
function getDateDiff(dateTimeStamp){

    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var halfamonth = day * 15;
    var month = day * 30;
    var now = new Date().getTime();
    var diffValue = now - dateTimeStamp;
    if(diffValue < 0){ result="刚刚";return;}
    var monthC =diffValue/month;
    var weekC =diffValue/(7*day);
    var dayC =diffValue/day;
    var hourC =diffValue/hour;
    var minC =diffValue/minute;
    if(monthC>=1){result="超时";}
    else if(weekC>=1){result="超时";}
    else if(dayC>=1){result="超时";}
    else if(hourC>=1){result=""+ parseInt(hourC) +"小时前";}
    else if(minC>=1){result=""+ parseInt(minC) +"分钟前";}
    else result="刚刚";
    return result;
}

//监听值的变化，自适应---------------------
$('#inputword').bind('input propertychange', function(a) {
    var a= a.target;
    //自适应高度
    var wid=document.getElementById("inputword").style.width;
    if(a.cols==0){a.cols=20}
    var col=a.cols;
    var val=a.value.length;
    var rownum=1;
    if(val>=col){
        rownum=Math.ceil(val/col);
        if(rownum>=3){
            a.style.overflowY="auto";
            a.rows=3;
        }else{
            a.rows=rownum;
        }
    }
    var inputword=$("#inputword")[0];//callback评论输入框
    var changeheight;
    if(typeof window.getComputedStyle!='undefined'){
        changeheight=window.getComputedStyle(inputword,null)["height"];
    }else if(inputword.currentStyle){
        changeheight=parseInt(inputword.currentStyle["height"]);
    }
    var pheight=parseFloat(changeheight)+2+"px";

    $(".main>p").css("height",pheight);
    changeheight=parseFloat(changeheight)+14+"px";
    $(".bottomnav").css("height",changeheight);
    //聊天区域调整位置
    $("#chatbody").css("bottom",changeheight);
});
//表情 输入框不能同时存在-------------------------------
$("#inputword").focus(function(){
    $(".hide").css("display","none");
    $("#facelist").css("display","none");
    //聊天区域调整位置
    var oldbottom=$("#chatbody").css("bottom");
    console.log(oldbottom);
    if(oldbottom!="45px"&&oldbottom!="43px"){
        var newbottom=parseFloat(oldbottom)-136+"px";
        $("#chatbody").css("bottom",newbottom);
    }

    tobottom();
});
//页面底部定位------------------------------------------
function tobottom(){
    var chatbody= document.getElementById('chatbody');
    chatbody.scrollTop = chatbody.scrollHeight;
}
//===================================================获取用户ID=========================================================
var id=$.cookie("MYID");
if(!id){location.href="login.html";}
var regotherid=/(otherid=)([a-zA-Z0-9]*)/;
var otherid = urlfrom.match(regotherid).splice("=")[2];
var myimg="<img src='img/af8.png' onclick='gotomy()'>";
var mynick="";
if($.cookie("MYAVA")&& $.cookie("MYAVA")!="null"){
    myimg="<img src='"+imgurl+$.cookie("MYAVA")+"' onclick='gotomy()'>";
    mynick=$.cookie("MYNICK");
}
//跳转按键
document.getElementsByClassName("mweb_modal_back_button")[0].onclick=function(){history.go(-1);};
function gotoother(){location.href="otherpeoplepage.html?otherid="+otherid;}
function gotomy(){location.href="setpage.html";}
//刷新
var currentIndex=1;
$("#ref").click(function(){
    $("#chatbody .mychatword").remove();
    $("#chatbody .otherchatword").remove();
    getms();
});
//获取他人信息
$.ajax({
    type: "post",
    //提交的网址
    url: "https://www.pulu.com/webapi/api/PuluUser/GetUserProc",
    //返回数据的格式
    data:{"userId":otherid},
    datatype: "json",
    //成功返回之后调用的函数
    success:function(data){
        $(".page_title.unified span").html(data.Data.userNick);
    }
});
var oldtim="";//保存时间
//收信息
function getms(){
    $.ajax({
        type:"get",
        datatype:"json",
        url:getmessageurl+"?userId="+id+"&friendId="+otherid,
        success:function(d){
            console.log(d);
            if(d.Data&& d.Data.length>0){
                var newtime="";
                for(var i=0;i< d.Data.length;i++){
                    //文字
                    var arr1= d.Data[i].msg;
                    arr1=codetoface(arr1);
                    //对方头像
                    if(d.Data[i].userHeadImg){
                        otherimg="<img src='http://42.62.66.198:8003/"+d.Data[i].userHeadImg+"' onclick='gotoother()'>";
                    }else{
                        otherimg="<img src='img/af8.png' onclick='gotoother()'>";
                    }
                    var timeword=getDateDiff(getDateTimeStamp(d.Data[i].ctime));

                    if(!timeword){
                        newtime="刚刚";
                    }else if(timeword=="超时"){
                        newtime=(d.Data[i].ctime).match(/[0-9\-T\:]+/)[0].replace(/T/g,' ').replace(/[0-9]{4}-/,"").substr(0,11);
                    }else{
                        newtime=timeword;
                    }
                    var showtime="<div class='showtime'><span>"+newtime+"</span></div>";
                    if(newtime!=oldtim){
                        oldtim=newtime;
                    }else{
                        showtime="";
                    }
                    //对方发给我
                    if(d.Data[i].userId!=id){
                        $("#chatbody").append("<div class='otherchatword'>"+showtime+" <div class='img' style='height:33px;width:33px;'> "+otherimg+" </div> <div class='word'><p class='arrow'></p>"+arr1+"</div> </div>");
                    }
                    else{
                        $("#chatbody").append("<div class='mychatword'>"+showtime+"<div class='img' style='height:33px;width:33px;'>"+myimg+"</div> <div class='word'><p class='arrow'></p>"+arr1+"</div> </div>");
                    }
                };
                tobottom();}
            else{currentIndex--;}
        }
    });
}
getms();
//发信息
function sendms(){
    $("#facelist").css("display","none");
    $("#chatbody").css("bottom","45px");
    //$('#inputword').attr("rows",1);
    $(".main>p").css("height","31px");
    $(".bottomnav").css("height","45px");
    //判断是否有表情
    var arr1=document.getElementById("inputword").value;
    arr1=codetoface(arr1);
    $.ajax({
        type:"post",
        datatype:"json",
        url:addmessageurl,
        data:{"userId":id,"friendId":otherid,"msg":document.getElementById("inputword").value},
        success:function(d){
            console.log(d);
            document.getElementById("inputword").rows="1";
            $("#facelist").css("display","none");
            $("#chatbody").css("bottom","45px");
            //$('#inputword').attr("rows",1);
            $(".main>p").css("height","31px");
            $(".bottomnav").css("height","45px");
            var newDate=new Date();
            var strtime=newDate.toISOString();
            var newtime=(strtime).match(/[0-9\-T\:]+/)[0].replace(/T/g,' ').replace(/[0-9]{4}-/,"").substr(0,11);
            var showtime="<div class='showtime'><span>"+newtime+"</span></div>";
            if(newtime!=oldtim){
                oldtim=newtime;
            }else{
                showtime="";
            }
            $("#chatbody").append("<div class='mychatword'>"+showtime+"<div class='img' style='height:33px;width:33px;'>"+myimg+"</div> <div class='word'><p class='arrow'></p>"+arr1+"</div> </div>");
            //console.log($(".img").width());
            $("#inputword").val("");
            tobottom();
            $("#sendword").attr("class","cannotclick");
            //$("#inputword").blur();
        }
    });
}
//删除全部信息
$("#delall").click(function(){
    $.ajax({
        type:"post",
        datatype:"json",
        url:delallmessageurl,
        data:{"userId":id,"friendId":otherid},
        success:function(d){
            $("#chatbody .mychatword").remove();
            $("#chatbody .otherchatword").remove();
        }
    });
});
//删除单条
var timeout ;
$("#mydiv").mousedown(function() {
    timeout = setTimeout(function() {
        $("#mydiv").text("in");
    }, 2000);
});
$("#mydiv").mouseup(function() {
    clearTimeout(timeout);
    $("#mydiv").text("out");
});
$("#mydiv").mouseout(function() {
    clearTimeout(timeout);
    $("#mydiv").text("out");
});
//发送
var sendword=document.getElementById("sendword");//按钮
document.onkeydown=function(event){
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if(e && e.keyCode==13){ // enter 键
        if(document.getElementById("inputword").value&&!document.getElementById("inputword").value.match(/^\s+$/g)){sendms();}
    }
};
sendword.onclick=function(){
    if(document.getElementById("inputword").value&&!document.getElementById("inputword").value.match(/^\s+$/g)){sendms();}
};
//打开表情
var mySwiper;
$(".face").click(function(){
    if(document.getElementById("facelist").style.display==="block"){
        document.getElementById("facelist").style.display="none";
        //聊天页面
        if(/chatingonepeople/.test(location.href)){
            //聊天区域调整位置
            var oldbottom=$("#chatbody").css("bottom");
            var newbottom=parseFloat(oldbottom)-136+"px";
            $("#chatbody").css("bottom",newbottom);
            tobottom();
        }
    }else if(document.getElementById("facelist").style.display==="none"){
        document.getElementById("facelist").style.display="block";
        //聊天页面
        if(/chatingonepeople/.test(location.href)){
            //聊天区域调整位置
            var oldbottom=$("#chatbody").css("bottom");
            var newbottom=parseFloat(oldbottom)+136+"px";
            $("#chatbody").css("bottom",newbottom);
            tobottom();
        }
        if(!mySwiper){
            mySwiper = new Swiper ('.swiper-container', {
                paginationClickable: true,
                touchRatio : 1,
                initialSlide :0,
                pagination: '.swiper-pagination'
            })
        }
    }
});

//发送表情
function sendface(e){
    var face=e.dataset.key;
    $("#sendword").attr("class","");
    $("#inputword").insertAtCaret(face);
    //$("#inputword").blur();
}
//上传图片
document.getElementById("addimgbtn").addEventListener( 'change',createimg,false );
function createimg(){
    var id = conn.getUniqueId();
    var msg = new WebIM.message('img', id);
    var input = document.getElementById('addimgbtn');//选择图片的input
    var file = WebIM.utils.getFileUrl(input);
    console.log(file);
    var allowType = {
        "jpg": true,
        "jpeg": true,
        "gif": true,
        "png": true,
        "bmp": true
    };
    if ( file.filetype.toLowerCase() in allowType ) {
        var imgurl="";
        msg.set({
            apiUrl: WebIM.config.apiURL,
            file: file,
            to: otherid,
            onFileUploadError: function ( error ) {
                console.log("发送图片失败");
            },//图片上传失败
            onFileUploadComplete: function ( data ) {
                console.log("发送图片部分");
                //图片地址：data.uri + '/' + data.entities[0].uuid;
                console.log(data.uri + '/' + data.entities[0].uuid);
                imgurl=data.uri + '/' + data.entities[0].uuid;
            },
            success: function ( id, serverMsgId ) {
                console.log("发送图片成功");
                console.log(id);
                console.log(serverMsgId);
                var newtime=GetDateT();
                if(newtime==oldtime){
                    $("#chatbody").append("<div class='mychatword'> <div class='img' style='height:33px;width:33px;'>"+myimg+"</div> <div class='word' style='padding:2px;'><p class='arrow'></p><img onclick='showbigimg(this)' class='getimg' src='"+imgurl+"' onload='tobottom()'></div> </div>");
                }else{
                    oldtime=newtime;
                    $("#chatbody").append("<div class='mychatword'> <div class='showtime'><span>"+newtime+"</span></div>  <div class='img' style='height:33px;width:33px;'>"+myimg+"</div> <div class='word' style='padding:2px;'><p class='arrow'></p><img onclick='showbigimg(this)' class='getimg' src='"+imgurl+"' onload='tobottom()'></div> </div>");
                }

            },//图片消息发送成功
            flashUpload: WebIM.flashUpload
        });
        conn.send(msg.body);
    }
};